package com.huiquan.inspection.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.ModelAndView;

import com.huiquan.analysis.domain.User;
import com.huiquan.framework.base.BaseService;
import com.huiquan.framework.utils.GetListUtil;
import com.huiquan.inspection.dao.ReportDao;
import com.huiquan.inspection.domain.Report;

@Service
public class ReportService extends BaseService {

	@Autowired
	private ReportDao reportDao;

	/**
	 * 获取报告单列表
	 * 
	 * @param startStr
	 * @param keyword
	 * @param exactSearchFlag
	 * @return
	 */
	public Map<String, Object> getList(String startStr, String keyword, String countPerPageStr, String exactSearchFlag) {
		int start = startStr == null ? 1 : Integer.parseInt(startStr);
		boolean exactFlag = exactSearchFlag != null && exactSearchFlag.equals("1");

		Map<String, Object> param = new HashMap<>();
		if (keyword != null && !keyword.isEmpty()) {
			param.put("keyword", exactFlag ? keyword : "%" + keyword + "%");
		}
		int totalSize = reportDao.retrieveSize(param);

		Map<String, Integer> pageNo = new HashMap<>();
		if (countPerPageStr != null && !countPerPageStr.isEmpty()) {
			int countPerPage = Integer.parseInt(countPerPageStr);
			pageNo = GetListUtil.getPageNoParam(totalSize, start + "", countPerPage);
			param.put("countPerPage", countPerPage);
		} else {
			pageNo = GetListUtil.getPageNoParam(totalSize, start + "");
		}
		int endPage = pageNo.get("endPage");
		start = pageNo.get("start");
		int startIndex = pageNo.get("startIndex");

		List<Report> list = new ArrayList<>();

		if (startIndex < totalSize) {
			param.put("startIndex", startIndex);
			list = reportDao.retrieveList(param);
		}

		Map<String, String> showSearch = new LinkedHashMap<>();
		showSearch.put("keyword", "名称");

		Map<String, Object> map = GetListUtil.getReturnMap2(totalSize, start, startIndex, endPage, list, null);
		map.put("showSearch", showSearch);
		return map;
	}

	/**
	 * 修改报告单中disable状态
	 * 
	 * @param id
	 * @param current
	 * @param user
	 */
	public void updateDisable(Long id, Integer current, User user) {
		reportDao.updateDisable(id, current, user);
	}

	/**
	 * 添加报告单
	 * 
	 * @param name
	 * @param user
	 * @return
	 */
	public int insert(String name, User user) {
		int existSize = reportDao.retrieveSizeByName(name);
		if (existSize > 0) {
			return 1;
		}
		Report report = new Report();
		report.setName(name);
		report.setCreatorId(user.getUserId());
		report.setCreatorName(user.getRealName());
		report.setModifierId(user.getUserId());
		report.setModifierName(user.getRealName());
		reportDao.insert(report);
		return 0;
	}

}
